package ThreadDemo3;

/**
 * Created with IntelliJ IDEA.
 * Description:锁操作
 * User: 阿宾
 * Date: 2025-03-24
 * Time: 20:01
 */
class Test{
    public int count = 0;

    synchronized public void add(){
            count++;
    }
    synchronized public static void func(){

    }
    /*//和上述方式等价
    public static void func(){
        synchronized (Test.class){

        }
    }*/

}

public class ThreadDemo2 {
    public static void main(String[] args) throws InterruptedException {
        //创建对象
        Test test = new Test();

        //创建两个线程，每个线程对count加5W次
        Thread t1 = new Thread(
                ()->{
                    for (int i = 0; i < 50000; i++) {
                        test.add();
                    }
                }
        );
        Thread t2 = new Thread(
                ()->{
                    for (int i = 0; i < 50000; i++) {
                        test.add();
                    }
                }
        );
        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("count = "+ test.count);//正确结果
    }
}